<template>
  <div class="logindemo">
    <el-card class="login-form-layout">
      <el-form autocomplete="on" :model="user" :rules="rules" ref="loginForm" status-icon label-position="left"
        @keydown.native="handleKeydown">
        <div style="text-align: center">
          <!-- <svg-icon icon-class="login-mall" style="width: 56px;height: 56px;color: #409EFF"></svg-icon> -->
        </div>
        <h2 class="login-title color-main">电商系统</h2>
        <el-form-item prop="name">
          <el-input name="name" type="text" v-model="user.name" autocomplete="on" placeholder="请输入用户名">
            <span slot="prefix">
              <!-- <svg-icon icon-class="user" class="color-main"></svg-icon> -->
            </span>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :type="pwdType" v-model="user.password" @keyup.enter.native="submit"
            autocomplete="on" placeholder="请输入密码" show-password>
            <span slot="prefix">
              <!-- <svg-icon icon-class="password" class="color-main"></svg-icon> -->
            </span>
            <span slot="suffix" @click="showPwd">
              <!-- <svg-icon icon-class="eye" class="color-main"></svg-icon> -->
            </span>
          </el-input>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item>
          <el-row :gutter="24">
            <el-col :span="16" :offset="0">
              <el-input v-model="user.code" placeholder="请输入验证码" maxlength="4" /><!-- 加限制 -->
            </el-col>
            <el-col :span="8" :offset="0">
              <vue-image-verify ref="captchaComponent" @getIdentifyCode="getIdentifyCodes" /> <!-- 使用自定义验证码组件 -->
            </el-col>
          </el-row>
        </el-form-item>


        <el-form-item style="margin-bottom: 60px">
          <el-button style="width: 100%" type="primary" :loading="loading" @click.native.prevent="submit">登录</el-button>
        </el-form-item>

      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { Loading } from 'element-ui';
import Toast from "assert";
import vueImageVerify from './vueImageVerify.vue';
export default {
  components: { vueImageVerify },
  name: "LoginPage",
  data() {
    return {
      loading: false,
      pwdType: "password",
      user: {
        name: '',
        password: '',
        code: '' // 用于验证码
      },
      rules: {
        name: [{
          required: true,
          message: '用户名不能为空',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '密码不能为空',
          trigger: 'blur'
        }],
        code: [{
          required: true,
          message: '验证码不能为空',
          trigger: 'blur'
        }],
      },
    };
  },
  computed: {
    // 通过mapState辅助函数将Vuex中的message状态映射到组件的计算属性中，方便使用
    ...mapState('user', ['message'])
  },
  mounted() {
    if (this.message.show) {
      // 使用Element UI的$message组件显示消息框，根据message中的类型和内容进行展示
      this.$message({
        type: this.message.type,
        message: this.message.content,
        showClose: true
      });
      // 显示完消息框后，将消息的显示状态重置为false，避免重复显示
      this.$store.commit('user/SET_MESSAGE', {
        show: false,
        type: '',
        content: ''
      });
    }
  },
  methods: {
    //登录button上加载提示：小圆圈控制
    startLoading: function () {
      this.loading = Loading.service({
        lock: true,
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    endLoading: function () {
      this.loading.close()
    },
    //小眼睛选择密码是否可见
    showPwd() {
      if (this.pwdType === "password") {
        this.pwdType = "";
      } else {
        this.pwdType = "password";
      }

    },
    // 获取验证码的方法
    getIdentifyCodes(value) {
      console.log('生成的验证码:', this.valiatecode, '用户输入的验证码:', this.user.code);
      console.log('验证码:', value);
      this.valiatecode = value.toLowerCase(); // 存储生成的验证码值
      if (this.verify.toLowerCase() != value.toLowerCase()) {
        Toast.fail('验证码有误')
        return false;
      }
      // 这里可以添加逻辑处理验证码以及与后端交互的部分
      // 根据业务需求，你可以请求新的验证码
      this.fetchNewCaptcha();
      return true;
    },
    handleLogin() { // 确保这里没有多余的符号
      // 验证码判断
      if (this.valiatecode.toLowerCase() !== this.user.code.toLowerCase()) {

        this.$notify({
          title: '警告',
          message: '验证码错误',
          type: 'warning',
          duration: 2000
        });
      }
      else {
        return true;
      }
    },
    // 监听回车键调用登录
    handleKeydown(event) {
      if (event.key === "Enter") {
        this.submit();
      }
    },

    //提交表单，登录验证
    submit() {
      this.$refs.loginForm.validate(valid => {//对应el-form的ref属性
        if (!valid) {
          console.log("参数验证不合法！");
          this.loading = false; // 停止加载状态
          return false; // 终止后续逻辑
        }
        this.loading = true;//开始登录button上小圆圈转
        // 调用 handleLogin 检验验证码是否正确
        if (!this.handleLogin()) { // 如果验证码错误
          this.loading = false; // 停止加载状态
          this.refreshCaptcha();
          return false; // 终止后续逻辑
        }
        if (valid) {//表单正确格式填写

          this.$axios.post('http://localhost:8080/login/log', this.user).then((res) => {//axios发送post请求，后台验证
            if (res.data.message == "登录成功") {
              this.$store.dispatch("user/SET_DATA", res.data.data.User)
              this.$router.push({ name: 'HomePage' })//结合router/index.js规则，根据name跳转到指定url
            } else {
              this.loading = false;//登录错误，小圆圈不转
              this.$message({
                type: 'error',
                message: '用户名或密码或验证码错误',
                showClose: true
              });
              this.refreshCaptcha();
            }
          }).catch(() => {
            this.loading = false;//登录错误，小圆圈不转
            this.$message({
              type: 'error',
              message: '网络错误，请重试',
              showClose: true
            })
          });
        } else {
          console.log("参数验证不合法！");
          return false;
        }
      });
    },
    refreshCaptcha() {
      // 调用 vueImageVerify 组件中的生成验证码方法
      this.$refs.captchaComponent.createdCode();
    }



  }
};
</script>

<style scoped>
.login-form-layout {
  position: absolute;
  left: 0;
  right: 0;
  width: 360px;
  margin: 140px auto;
  border-top: 10px solid #409eff;
}

.login-title {
  text-align: center;
}

.login-center-layout {
  background: #409eff;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  margin-top: 200px;
}
</style>
